package com.example.zhihu.controller;

import com.example.zhihu.pojo.Users;
import com.example.zhihu.pojo.vo.AnswerVO;
import com.example.zhihu.pojo.vo.UserVO;
import com.example.zhihu.service.UserService;
import com.example.zhihu.utils.JSONResult;
import com.example.zhihu.utils.MD5Utils;
import com.example.zhihu.utils.PagedResult;
import io.swagger.annotations.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@RestController
@Api(value="用户接口", tags = {"用户的controller"})
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "用户上传头像",notes = "用户上传头像的接口")
    @ApiImplicitParams({
        @ApiImplicitParam(name="userId",value = "用户ID",required = true,dataType = "string",paramType = "query"),
        @ApiImplicitParam(name = "file",value = "头像路径", dataType = "file",paramType = "form")
    })
    @PostMapping(value = "/uploadFace", headers = "content-type=multipart/form-data")
    public JSONResult uploadFace(@RequestParam String userId,@ApiParam(value = "头像路径",required = true) @RequestParam("file") MultipartFile[] files) throws Exception{
        System.out.println(userId);
        System.out.println(files);
        if(StringUtils.isBlank(userId)) {
            return JSONResult.errorMsg("用户Id不能为空");
        }

        //文件保存路径
        String uploadPathDB = null;
        FileOutputStream fileOutputStream = null;
        String FILE_SPACE = "D:/zhihu_storage";
        InputStream inputStream = null;
        uploadPathDB = "/"+userId+ "/face";
        try {
            if(files != null && files.length > 0) {
                String fileName = files[0].getOriginalFilename();
                if(StringUtils.isNoneBlank(fileName)) {
                    //文件上传的最终保存路径
                    String finalFacePath = FILE_SPACE + uploadPathDB + "/" + fileName;
                    //设置数据库保存路径
                    uploadPathDB += ("/"+fileName);
                    File outFile = new File(finalFacePath);
                    if(outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()){
                        //创建父文件夹
                        outFile.getParentFile().mkdirs();
                    }
                    fileOutputStream = new FileOutputStream(outFile);
                    inputStream = files[0].getInputStream();
                    IOUtils.copy(inputStream,fileOutputStream);
                }
            } else {
                return JSONResult.errorMsg("上传出错");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return JSONResult.errorMsg("上传出错");
        } finally {
            if(fileOutputStream != null) {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        }

        Users user = new Users();
        user.setId(userId);
        user.setAvatar(uploadPathDB);
        userService.updateUser(user);
        return JSONResult.ok(uploadPathDB);
    }

    @ApiOperation(value="用户注册",notes = "用户注册的接口")
    @PostMapping("/register")
    public JSONResult register(@RequestBody Users user) throws Exception {
        System.out.println(user.getAccount());
        System.out.println(user.getPassword());
        //1.判断用户名和密码不为空
        if(StringUtils.isBlank(user.getAccount()) || StringUtils.isBlank(user.getPassword())) {
            return JSONResult.errorMsg("用户名和密码不能为空");
        }
        //2.判断用户名是否存在
        boolean usernameIsExit = userService.queryUserIsExit(user.getAccount());
        if(!usernameIsExit) {
            user.setName(user.getAccount());
            user.setAge("0");
            user.setEmail("0");
            user.setPhone("0");
            user.setSex(0);
            user.setState(1);
            user.setFanCount(0);
            user.setFollowCount(0);
            user.setReceiveCount(0);
            user.setCreateTime(new Date());
            user.setPassword(MD5Utils.getMD5Str(user.getPassword()));
            userService.saveUser(user);
        } else {
            return JSONResult.errorMsg("用户已存在");
        }
        user.setPassword("");
        return JSONResult.ok(user);
    }

    @ApiOperation(value = "用户登陆")
    @PostMapping("/login")
    public JSONResult login(@RequestBody Users user, HttpServletResponse response, HttpServletRequest request) throws Exception {

        if(StringUtils.isBlank(user.getAccount()) || StringUtils.isBlank(user.getPassword())){
            return JSONResult.errorMsg("用户名或密码不能为空");
        }
        Users result = userService.queryUserForLogin(user.getAccount(),MD5Utils.getMD5Str(user.getPassword()));

        if(result != null) {
            String token = UUID.randomUUID().toString();
            Map<String, String> map = new HashMap<>();
            map.put("token", token);
            map.put("id",result.getId());
            Cookie cookie = new Cookie("token", token);
            cookie.setPath(request.getContextPath());
            cookie.setMaxAge(30000);
            response.addCookie(cookie);
            return JSONResult.ok(map);
        } else {
            return JSONResult.errorMsg("用户名或密码不正确，请重试...");
        }

    }

    @ApiOperation(value = "用户列表")
    @GetMapping("/userList")
    public JSONResult userList(@RequestParam(required = false) String userId) {
        List<UserVO> list= userService.userList();
        for(UserVO u : list) {
            u.setFollow(userService.isFollow(u.getId(),userId));
        }
        return  JSONResult.ok(list);
    }

    @ApiOperation(value = "修改用户信息")
    @PostMapping("/updateUser")
    public JSONResult updateUser(@RequestBody Users user) {
        if(StringUtils.isBlank(user.getId())) {
            return JSONResult.errorMsg("信息有误");
        }
        userService.updateUser(user);
        return JSONResult.ok("修改成功");
    }

    @ApiOperation(value = "查询用户资料")
    @GetMapping("/queryUser")
    public JSONResult queryUser(@RequestParam(required = true) String id, @RequestParam(required = false) String fanId) {

        if (StringUtils.isBlank(id)) {
            return JSONResult.errorMsg("id不能为空");
        }

        Users user = userService.queryUser(id);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);
        userVO.setFollow(userService.isFollow(id, fanId));
        return JSONResult.ok(userVO);
    }

    @ApiOperation("关注用户")
    @GetMapping("/beFans")
    public JSONResult beFans(@RequestParam String userId, @RequestParam String fanId) {
        userService.saveUserFans(userId,fanId);
        return JSONResult.ok("关注成功");
    }

    @ApiOperation("取关用户")
    @GetMapping("/nobeFans")
    public JSONResult nobeFans(@RequestParam String userId, @RequestParam String fanId) {
        userService.deleteUserFans(userId,fanId);
        return JSONResult.ok("取消关注成功");
    }

    @ApiOperation("用户点赞的回答")
    @GetMapping("/showUserLike")
    public JSONResult userLikeAnswer(@RequestParam String userId) {
        List<AnswerVO> list = userService.queryUserLike(userId);
        for(AnswerVO a : list) {
            String answerId = a.getId();
            boolean userLikeAnswer = userService.isUserLikeAnswer(userId,answerId);
            boolean userCollectAnswer = userService.isUserCollectAnswer(userId,answerId);
            a.setLike(userLikeAnswer);
            a.setCollect(userCollectAnswer);
        }
        return JSONResult.ok(list);
    }

    @ApiOperation("用户收藏的回答")
    @GetMapping("/showUserCollect")
    public JSONResult userCollectAnswer(@RequestParam String userId) {
        List<AnswerVO> list = userService.queryUserCollect(userId);
        for(AnswerVO a : list) {
            String answerId = a.getId();
            boolean userLikeAnswer = userService.isUserLikeAnswer(userId,answerId);
            boolean userCollectAnswer = userService.isUserCollectAnswer(userId,answerId);
            a.setLike(userLikeAnswer);
            a.setCollect(userCollectAnswer);
        }
        return JSONResult.ok(list);
    }

    @ApiOperation("用户关注者的回答")
    @GetMapping("/showUserFollow")
    public JSONResult userFollowAnswer(@RequestParam String userId) {
        List<AnswerVO> list = userService.queryUserFollow(userId);
        return JSONResult.ok(list);
    }
}
